package com.bawei.module_mine.tengxun.websocket

import android.util.Log
import com.bawei.module_mine.tengxun.TengxunActivity
import com.blankj.utilcode.util.ToastUtils
import okhttp3.Response
import okhttp3.WebSocket
import okhttp3.WebSocketListener
import okio.ByteString
import org.json.JSONObject
import java.lang.ref.WeakReference
import kotlin.math.roundToInt

class SafeWebSocketListener(activity: TengxunActivity) : WebSocketListener() {
    private val activityRef = WeakReference(activity)

    override fun onMessage(webSocket: WebSocket, text: String) {
        val activity = activityRef.get() ?: return
        val json = JSONObject(text)
        val type = json.optInt("type")
        if (type == 5) {
            val data = json.optJSONObject("data")
            val username = data?.optString("username")
            if (!username.isNullOrEmpty()) {
                activity.runOnUiThread {
                    ToastUtils.showShort("$username 加入直播间")
                }
            }
        }
        if (type == 1) {
            val data = json.optJSONObject("data")
            val roomId = data?.optString("room_id")
            val count = data?.optInt("count")
            val money = data?.optDouble("money")
            val time = data?.optInt("time")
            val createTime = data?.optString("createTime")

            activity.runOnUiThread {
                activity.showRedPacketDialog(count!!, money!!.roundToInt())
            }
        }
    }

    override fun onMessage(webSocket: WebSocket, bytes: ByteString) {}

    override fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?) {}

    override fun onOpen(webSocket: WebSocket, response: Response) {
        val activity = activityRef.get() ?: return
        Log.d("WebSocket", "redPacket---open")
        Log.d("WebSocket", "连接已建立，房间号:${activity.roomId}")
        Log.d("WebSocket", webSocket.request().url.toString())
    }

    override fun onClosed(webSocket: WebSocket, code: Int, reason: String) {
        Log.d("WebSocket", "redPacket---close")
    }
}